package com.example.administrator.wallet.view.activity;

import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.example.administrator.wallet.MainActivity;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.AgainBackGrid2Adapter;
import com.example.administrator.wallet.adapter.AgainBackupsGridAdapter;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.TokenBean;
import com.example.administrator.wallet.utils.AESUtils;
import com.example.administrator.wallet.utils.ListDataSave;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ExtendedKey;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ValidationException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip39.SeedCalculator;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.AddressIndex;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.BIP44;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.CoinPairDerive;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.ECDSASignature;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.Base64;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.KECCAK256;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.Bitcoin;
import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.BitcoinTest;
import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.Ethereum;

public class AgainBackupsActivity extends BaseActivity {


    @Bind(R.id.finish_img)
    ImageButton finishImg;
    @Bind(R.id.view_title)
    TextView viewTitle;
    @Bind(R.id.recovery)
    TextView recovery;
    @Bind(R.id.iGridView)
    GridView iGridView;
    @Bind(R.id.iGridView2)
    GridView iGridView2;
    @Bind(R.id.submit)
    Button submit;
    @Bind(R.id.activity_again_backups)
    RelativeLayout activityAgainBackups;
    private List<String> getDatas;
    private List<String> datas;
    private List<String> datas2;
    private AgainBackGrid2Adapter adapter;
    private AgainBackupsGridAdapter gridAdapter;
    private SharedPreferences wallet;
    private SharedPreferences.Editor edit;
    private List<String> zhujici;
    private TokenBean tokenBean;
    private String mBitcoinAddress;
    private String mBitcoinPrivateKey;
    private String mBitcoinPublicKey;
    private String mEtherPrivateKey;
    private String mEtherPublicKey;
    private String mEtherAddress;
    private EthECKeyPair mEtherKeyPair;
    private boolean isTestNet = true;
    private BitCoinECKeyPair parse;
    private BitCoinECKeyPair mBitcoinKeyPair;

    @Override
    public void init() {
        wallet = getSharedPreferences("wallet", MODE_PRIVATE);
        edit = wallet.edit();
        setStatuColor();
        finishImg.setVisibility(View.VISIBLE);
        viewTitle.setText(R.string.copy_zhujici);
        initData();
        initAdapter();
        intf();
    }

    private void intf() {
        datas2 = new ArrayList<>();
        datas2.add("adapter");
        datas2.clear();
        gridAdapter = new AgainBackupsGridAdapter(this, datas2);
        iGridView.setAdapter(gridAdapter);
        adapter.getPst(new AgainBackGrid2Adapter.OnClick() {
            @Override
            public void click(int psw, boolean isSelect) {
                if (isSelect) {
                    datas2.remove(datas.get(psw));
                } else {
                    datas2.add(datas.get(psw));
                }
                gridAdapter.notifyDataSetChanged();
                onClick();
            }
        });
        onClick();
    }

    private void onClick() {
        if (datas2.size() == 12) {
            submit.setBackground(getResources().getDrawable(R.drawable.splash_but_bg));
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("TAG_Datas", datas2.toString());
                    boolean compare = compare(zhujici, datas2);
                    if (compare) {
                        final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
                        long num = (long) ((Math.random() * 9 + 1) * Math.pow(10, 20));
                        long num2 = (long) ((Math.random() * 9 + 1) * 10);
                        String random = num + "" + num2;
                        Log.e("TAG", random);
                        reqequestManager.httpPost(Api.BaseUrl + Api.Request_Token, Api.getLoginParams(random), new IRequestCallback() {
                            @Override
                            public void onSuccess(String Response) {
                                edit.putInt("count", 3);
                                edit.commit();
                                Gson gson = new Gson();
                                tokenBean = gson.fromJson(Response, TokenBean.class);
                                SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "token", tokenBean.getData().getAccess_token());
                                byte[] seed = new SeedCalculator().calculateSeed(zhujici, "");
                                try {
                                    ExtendedKey extendedKey = ExtendedKey.create(seed);
                                    ECKeyPair master = (ECKeyPair) extendedKey.getMaster();
                                    AddressIndex index_Ethereum = BIP44.m().purpose44()
                                            .coinType(Ethereum)
                                            .account(0)
                                            .external()
                                            .address(0);
                                    AddressIndex index_Bitcoin = BIP44.m().purpose44()
                                            .coinType(BitcoinTest)
                                            .account(0)
                                            .external()
                                            .address(0);
//                                    AddressIndex index_USDT = BIP44.m().purpose44()
//                                            .coinType(Bitcoin)
//                                            .account(0)
//                                            .external()
//                                            .address(0);
                                    CoinPairDerive pairDerive = new CoinPairDerive(extendedKey);
                                    mEtherKeyPair = (EthECKeyPair) pairDerive.derive(index_Ethereum);
                                    mBitcoinKeyPair = (BitCoinECKeyPair) pairDerive.derive(index_Bitcoin);
                                    mBitcoinAddress = mBitcoinKeyPair.getAddress();
                                    mBitcoinPrivateKey = mBitcoinKeyPair.getPrivateKey();
                                    mBitcoinPublicKey = mBitcoinKeyPair.getPublicKey();
                                    mEtherPrivateKey = mEtherKeyPair.getPrivateKey();
                                    mEtherPublicKey = mEtherKeyPair.getPublicKey();
                                    mEtherAddress = mEtherKeyPair.getAddress();


                                    String secretKey = AESUtils.generateSecretKey();
                                    String bitcoinKey = AESUtils.encrypt(mBitcoinPrivateKey, secretKey);
                                    String ethcoinKey = AESUtils.encrypt(mEtherPrivateKey, secretKey);

                                    String mEtherEncode = Base64.encode(mEtherAddress.getBytes());
                                    String mBitcoinEncode = Base64.encode(mBitcoinAddress.getBytes());
                                    String mEthPrivateKey = Base64.encode(mEtherPrivateKey.getBytes());
                                    String mBtcPrivateKey = Base64.encode(mBitcoinPrivateKey.getBytes());
                                    String s = Base64.encode(mBitcoinKeyPair.getRawPrivateKey());
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "bit_raw", s);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "eth_private-", mEtherPrivateKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "bit-", mBitcoinPublicKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "btc_private-", mBitcoinPrivateKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "eth", mEtherEncode);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "bit", mBitcoinEncode);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "secretKey", secretKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "eth_private", ethcoinKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "btc_private", bitcoinKey);
                                    SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "master", new String(seed));
                                    mRequestAddress(reqequestManager);
                                } catch (ValidationException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("TAG--Responcs", error);
                                SharedPrefsUtil.putValue(AgainBackupsActivity.this, "wallet", "count", 1);
                            }
                        });
                    } else {
                        Toast.makeText(AgainBackupsActivity.this, R.string.zhujici_error, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            submit.setBackground(getResources().getDrawable(R.drawable.againbackups_but_bg));
            submit.setOnClickListener(null);
        }
    }

    private void mRequestAddress(IRequestManager reqequestManager) {
        /*let s = "\x18Bitcoin Signed Message:\n"*/
        String mBitcoinMsg = "123456";
        String mEtherMsg = "123";
        String m = "\u0019Ethereum Signed Message:\n" + mEtherMsg.length() + mEtherMsg;
        String b = "\\x18Bitcoin Signed Message:\n" + mBitcoinMsg;
        byte[] bytes = KECCAK256.keccak256(b.getBytes()); //SHA256.doubleSha256(("Bitcoin Signed Message:" + mBitcoinMsg).getBytes());
        byte[] digest = KECCAK256.keccak256(m.getBytes());
        String mBitcoinSigntree = mBitcoinKeyPair.signBTC(bytes).toString();
        Log.e("TAG---Bit", mBitcoinSigntree);
        Log.e("TAG---M", mEtherAddress);
        Log.e("TAG---M", mBitcoinAddress);
        ECDSASignature s = mEtherKeyPair.sign(digest);
        String ss = s.toHex();
        Log.e("TAG---ETH", ss);
        Log.e("TAG", tokenBean.getData().getAccess_token());
        reqequestManager.httpPost(Api.BaseUrl + Api.Wallet_local, Api.getWalletLocalParams(tokenBean.getData().getAccess_token(), mEtherMsg, ss, "0x" + mEtherAddress, mBitcoinAddress, mBitcoinMsg, mBitcoinSigntree.toString()), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Log.e("TAG1111111111", Response);
                ActivityUtils.startActivity(AgainBackupsActivity.this, MainActivity.class);
                finish();
//                Toast.makeText(AgainBackupsActivity.this, Response, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String error) {
                Log.e("TAG222222", error);
                Toast.makeText(AgainBackupsActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initAdapter() {
        adapter = new AgainBackGrid2Adapter(this, datas);
        iGridView2.setAdapter(adapter);
    }

    private void initData() {
        ListDataSave dataSave = new ListDataSave(this, "wallet");
        zhujici = dataSave.getDataList("zhujici");
        List<String> random = getRandom(zhujici);
        datas = new ArrayList<>();
        datas.clear();
        datas.addAll(random);
    }

    public List<String> getRandom(List<String> datas) {
        List<String> temp = new ArrayList<>(datas);
        for (int i = datas.size(); i > 0; i--) {
            int ran = (int) (Math.random() * i);
            String randomValue = temp.remove(ran);
            temp.add(datas.size() - 1, randomValue);
        }
        return temp;
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_again_backups;
    }


    @OnClick({R.id.finish_img, R.id.recovery, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_img:
                finish();
                break;
            case R.id.recovery:
                ActivityUtils.startActivity(this, RecoveryActivity.class);
                break;
            case R.id.submit:
                break;
        }
    }


    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }
}
